import React, { useEffect ,useState} from 'react';
import { Button, Form, Input, Select, Space, Popconfirm, Tag, message, Image } from 'antd';
import { produce } from 'immer';
import PaginationComponent from "./../../components/PaginationComponent";
import TableComponent from "./../../components/TableComponent";
import AddOrEdit from "./addOrEdit";
import { getBannerList, updateBannerStatus } from './../../api/banner';
import type { PaginationProps, TableColumnsType, FormProps } from 'antd';
import type { bannerReqType, bannerStateType, bannerResType, bannerResDataType, bannerReqStateType } from '../../types/bannerType';
import styles from './index.module.scss';
import dayjs from 'dayjs';

const Banner: React.FC = () => {
  const [form] = Form.useForm();

  const [reqForm, setReqForm] = useState<bannerReqType>({
    title: "",
    status: 0,
    paging: {
      page: 1,
      size: 10
    }
  });
  const [isModalOpen,setIsModalOpen]=useState<boolean>(false);
  const [bannerId,setBannerId]=useState<number>();
  const [modalType,setModalType]=useState<'add'|'edit'>('add');

  const [data, setData] = useState<bannerResType>({
    count: 0,
    banners: []
  });

  const stateOpctions: bannerStateType[] = [{
    value: 0,
    label: "全部"
  }, {
    value: 1,
    label: "上架"
  }, {
    value: 2,
    label: "下架"
  }];
  // 表格
  const columns: TableColumnsType<bannerResDataType> = [
    {
      title: '序号',
      dataIndex: 'bannerId',
      key: 'bannerId',
    },
    {
      title: '封面',
      dataIndex: 'coverImgUrl',
      key: 'coverImgUrl',
      render: (_, { coverImgUrl }) => {
        return (<Image
          width={100}
          height={50}
          src={coverImgUrl}
        />)
      }
    },
    {
      title: '跳转类型',
      dataIndex: 'jumpType',
      key: 'jumpType',
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (_, { createTime }) => {
        return dayjs.unix(createTime).format("YYYY-MM-DD hh:mm:ss")
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, { status }) => {
        if (status === 1) {
          return <Tag color='volcano' key={status}>
            上架
          </Tag>
        } else {
          return <Tag color='gold' key={status}>
            下架
          </Tag>
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, { bannerId, status }) => (
        <Space size="middle">
          <Button type="link" onClick={()=>{
            setBannerId(bannerId);
            setIsModalOpen(true);
            setModalType('edit');
          }}>编辑</Button>
          <Popconfirm title={`确定${status === 1 ? '下' : '上'}架?`} onConfirm={() => { setBannerStatus({ bannerId, status: status === 1 ? 2 : 1 }) }}>
            <Button type="link">{`${status === 1 ? '下' : '上'}架`}</Button>
          </Popconfirm>
        </Space>
      )
    },
  ];
  // 查询
  const getDataList = () => {
    getBannerList(reqForm).then((res) => {
      if (res.code === 0) {
        setData(res.data)
      }
    });
  }
  // 设置选项内容
  const onFinish: FormProps<bannerReqType>['onFinish'] = (e) => {
    setReqForm(e);
  };

  // 分页切换
  const onChange: PaginationProps['onChange'] = (page, size) => {
    setReqForm(produce((draft) => {
      draft.paging = { page, size }
    }));
  };

  // 上下架
  const setBannerStatus = (e: bannerReqStateType) => {
    updateBannerStatus(e).then((res) => {
      if (res.code === 0) {
        getDataList();
        message.success("修改成功");
      }
    })
  }
  // 初始化加载
  useEffect(() => {
    getDataList()
  }, [reqForm])

  return (
    <>
      <div className={styles.Hader}>
        <h2>Banner配置</h2>
        <Form
          layout='inline'
          onFinish={onFinish}
          initialValues={reqForm}
          form={form}
        >
          <Form.Item<bannerReqType> name="title" style={{ width: 250 }} label="标题">
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item<bannerReqType> name="status" style={{ width: 250 }} label="状态">
            <Select
              style={{ width: '100%' }}
              options={stateOpctions}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType='submit'>查询</Button>
              <Button htmlType="reset" onClick={() => { form.resetFields() }}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      <TableComponent<bannerResDataType> data={data.banners} columns={columns}>
        <Button type="primary" onClick={()=>{
          setIsModalOpen(true);
          setModalType('add')}}>添加</Button>
      </TableComponent>
      <PaginationComponent count={data.count} onChange={onChange} />
      {/* 弹窗新增或编辑 */}
      <AddOrEdit isModalOpen={isModalOpen} bannerId={bannerId} type={modalType} handleCancel={()=>{
        setIsModalOpen(false);
        getDataList()
      }}/>
    </>
  );
};

export default Banner;